package com.kaisheng.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaisheng.entity.Contact;
import com.kaisheng.util.DBHelp;
import com.kaisheng.util.RowMapper;

public class ContactDao {

private DBHelp<Contact> db = new DBHelp<Contact>();
	
	public void save(Contact c) {
		String sql = "INSERT INTO t_contact(id,`name`,company,cellphone,phone,email,address,homepage,weibo,introduction,createtime,project_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
		db.executeSQL(sql,c.getId(),c.getName(),c.getCompany(),c.getCellphone(),c.getPhone(),c.getEmail(),c.getAddress(),c.getHomepage(),c.getWeibo(),c.getIntroduction(),c.getCreatetime(),c.getProject_id());
		
	}

	public List<Contact> findAllByProject_id(String project_id) {
	
			String sql = "SELECT  id,`name`,company,cellphone,phone,email,address,homepage,weibo,introduction,createtime,project_id FROM t_contact WHERE project_id = ? ORDER BY createtime DESC ";
			return db.executeQueryForList(sql,new ContactRowMapper() ,project_id);
	}
	
	public Contact findContactById(String id) {
		
		String sql = "SELECT id,`name`,company,cellphone,phone,email,address,homepage,weibo,introduction,createtime,project_id FROM t_contact WHERE id = ?";
		return db.executeQueryForObject(sql, new ContactRowMapper(),id);
	}

	public void updateContact(Contact c) {
		String sql ="UPDATE t_contact SET `name` = ?,company =?,cellphone =?,phone =?,email =?,address =?,homepage =?,weibo =?,introduction =? WHERE id =?";
		db.executeSQL(sql,c.getName(),c.getCompany(),c.getCellphone(),c.getPhone(),c.getEmail(),c.getAddress(),c.getHomepage(),c.getWeibo(),c.getIntroduction(),c.getId());
	}


	
	private class ContactRowMapper implements RowMapper<Contact>{

		public Contact mapRow(ResultSet rs) throws SQLException {
			Contact c = new Contact();
			c.setId(rs.getString("id"));
			c.setName(rs.getString("name"));
			c.setCompany(rs.getString("company"));
			c.setCellphone(rs.getString("cellphone"));
			c.setPhone(rs.getString("phone"));
			c.setEmail(rs.getString("email"));
			c.setAddress(rs.getString("address"));
			c.setHomepage(rs.getString("homepage"));
			c.setWeibo(rs.getString("weibo"));
			c.setIntroduction(rs.getString("introduction"));
			c.setCreatetime(rs.getString("createtime"));
			c.setProject_id(rs.getString("project_id"));
			
			return c;
		}
	}
	
	public void deleteContactById(String id) {
	String sql = "DELETE FROM t_contact WHERE id =?";
	db.executeSQL(sql, id);
		
	}


	



	

	
	
	
	
	
}
